package com.dust.yuheadline.common.exception;


import com.dust.yuheadline.common.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 全局异常处理
 *
 * @author 高翔宇
 * @since 2024-04-30, 周二, 15:11
 */
@ControllerAdvice
@Slf4j
public class MyExceptionHandler {

    /**
     * 处理不可控异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<?> exception(Exception e) {
        // e.printStackTrace();
        log.error("catch exception:{}", e.getMessage(), e);
        return new Result<>().error(500, "服务器异常，请稍后再试");
    }

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public Result<?> exception(CustomException e) {
        log.error("捕获异常：{}", e.getMessage(), e);
        return new Result<>().error(e.getErrorCode(), e.getErrorMessage());
    }
}
